import signal  # for keyboard events handling (press "Ctrl+C" to terminate recording)
import sys

import dashscope
from dashscope.audio.asr import *

from env import key
from audioRecognitionCallback import Callback, get_stream, get_result
from shelfMapper import task

# Set recording parameters
sample_rate = 16000  # sampling rate (Hz)
channels = 1  # mono channel
dtype = 'int16'  # data type
format_pcm = 'pcm'  # the format of the audio data
block_size = 3200  # number of frames per buffer


def get_pos():
    dashscope.api_key = key
    print('Initializing ...')

    callback = Callback()

    # Call recognition service by async mode, you can customize the recognition parameters, like model, format,
    # sample_rate For more information, please refer to https://help.aliyun.com/document_detail/2712536.html
    recognition = Recognition(
        model='paraformer-realtime-v2',
        # 'paraformer-realtime-v1'、'paraformer-realtime-8k-v1'
        format=format_pcm,
        # 'pcm'、'wav'、'opus'、'speex'、'aac'、'amr', you can check the supported formats in the document
        sample_rate=sample_rate,
        # support 8000, 16000
        semantic_punctuation_enabled=False,
        callback=callback)

    recognition.start()

    while True:
        if get_stream():
            data = get_stream().read(3200, exception_on_overflow=False)
            recognition.send_audio_frame(data)
            result = get_result()
            if result:
                x, y = task(result)
                break
        else:
            print("错误：stream is not initialized")
            x, y = 0.0, 0.0
            break

    recognition.stop()
    print(f"x: {x}, y: {y}")
    return x, y


# main function
if __name__ == '__main__':
    goal_ok = False
    while not goal_ok:
        while True:
            x, y = get_pos()
            if x != 0.0 or y != 0.0:
                break
        print(f"设置终点x: {x}, y: {y}")
